<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片轮播</title>
    <style>
        div{
            width: 400px;
            margin: 10% auto;
        }
        img{
            width: 400px;
            display: none;
        }
        img.active{
            display: block;
        }

    </style>
</head>

<body>
<div class="carousel">
    <img src="image/1.jpg" class="active">
    <img src="image/2.jpg">
    <img src="image/3.jpg">
    <button class="active"></button>
    <button ></button>
    <button ></button>
</div>

<script>
    let index = 0;
    const images = document.querySelectorAll(".carousel img");
    const total = images.length;
    let timer = null;

    function startCarousel() {
        if (timer) return;
        timer = setInterval(function () {
            images[index].classList.remove("active");
            index = (index + 1) % total;
            images[index].classList.add("active");
        }, 2000);
    }

    function stopCarousel() {
        clearInterval(timer);
        timer = null;
    }

    const carousel = document.querySelector(".carousel");
    carousel.addEventListener("mouseenter", startCarousel);
    carousel.addEventListener("mouseleave", stopCarousel);
</script>
</body>
</html>
